<template>
  <div >
    <div class="search">
      <input type="text" v-model="keyword" class="search-input" placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" v-show="keyword" ref="search">
      <ul class="search-list">
        <li class="search-item border-bottom"
          v-for="item of list"
          :key="item.id"
          @click="handleCityClick(item.name)"
        >
          {{item.name}}
        </li>
        <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      list: [],
      keyword: '',
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.name.indexOf(this.keyword) > -1
                || value.spell.indexOf(this.keyword) > -1)
            {
              result.push(value)
            }
          })
        }
        this.list = result
      },100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  },
  deactivated () {
    this.keyword = ''
  },
  methods: {
    handleCityClick (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  }
}

</script>

<style lang="stylus" scoped>
  @import '~@/assets/styles/variables.styl'
  .search
    background: $bgcolor
    text-align: center
    padding: 0 .2rem 0.2rem
    .search-input
      width: 100%
      line-height: 2rem
      box-sizing: border-box
      border-radius: .4rem
      text-align: center
      color: #666
  .search-content
    z-index: 1
    position: absolute
    overflow: hidden
    top: 5.5rem
    right: 0
    left: 0
    bottom: 0
    background: #fff
    .search-list
      padding: 0
      .search-item
        list-style:none
        padding-left: .5rem
</style>





